package com.surelution.lansao;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class RegisterUtil {
	
	public static HttpClient buildClient() {
        DefaultHttpClient httpclient = new DefaultHttpClient();
		return httpclient;
	}
	public static HttpClient buildClient(String username, String pwd) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
//		httpclient.a
		try {
			//TODO S
			HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN?");

			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("username", username));
			nvps.add(new BasicNameValuePair("pwd", pwd));
			nvps.add(new BasicNameValuePair("imgcode", ""));
			nvps.add(new BasicNameValuePair("f", "json"));

			httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

			HttpResponse response = httpclient.execute(httpost);
			HttpEntity entity = response.getEntity();
//			entity = response.getEntity();

			System.out.println("Login form get: " + response.getStatusLine());

			System.out.println("Post logon cookies:");
			List<Cookie> cookies = httpclient.getCookieStore().getCookies();
			if (cookies.isEmpty()) {
				System.out.println("None");
			} else {
				for (int i = 0; i < cookies.size(); i++) {
					System.out.println("- " + cookies.get(i).toString());
				}
			}
			EntityUtils.consume(entity);
		} catch(Exception e) {

		}
		return httpclient;
	}
	
	private static void accountInfoSubmit(HttpClient httpclient) throws Exception {
		HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/register?t=ajax-response&lang=zh_CN");
		 List <NameValuePair> nvps = new ArrayList <NameValuePair>();
       nvps.add(new BasicNameValuePair("err", "false"));
       nvps.add(new BasicNameValuePair("account", "测试小哥"));
       nvps.add(new BasicNameValuePair("intro", "不测怎么用"));
       nvps.add(new BasicNameValuePair("country", "中国"));
       nvps.add(new BasicNameValuePair("province", "上海"));
       nvps.add(new BasicNameValuePair("city", "嘉定"));
       nvps.add(new BasicNameValuePair("type", "1"));
       nvps.add(new BasicNameValuePair("ajax", "1"));

       httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
       HttpResponse response = httpclient.execute(httpost);
       HttpEntity entity = response.getEntity();
       entity.writeTo(System.out);
       EntityUtils.consume(entity);
	}
	
	private static String getSmVerifyCode(HttpClient httpclient) throws Exception {
		HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/realname?action=sendsmsverifycode&lang=zh_CN");
		 List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("sendmobile", "+8618001863596"));
        nvps.add(new BasicNameValuePair("ajax", "1"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        entity.writeTo(System.out);
        EntityUtils.consume(entity);
    
		Scanner scanner = new Scanner(System.in);
		System.out.println("input the mobile code");
		String s = scanner.nextLine();
		scanner.close();
		return s;
	}
	
	private static void registerProcess() throws Exception {
    	HttpClient hc = buildClient();
    	loadEmailVerifyTemplate(hc);
    	String verifyCd = getSmVerifyCode(hc);
    	String[] ss = uploadIDCard(hc);
    	if(ss != null) {
    		submitDetailedInfo(hc,verifyCd, ss[4], ss[5], ss[6]);
    		accountInfoSubmit(hc);
    	}
    }

    public static void main(String[] args) throws Exception {
    	registerProcess();
    	HttpClient httpclient = buildClient("uyytrtrgfdsgfjhhgjfhfdgd@weixindingcan.com", "96e79218965eb72c92a549dd5a330112");
    	String[] words = uploadImg(httpclient);
    	String imgCode = words[1];
    	imgCode = imgCode.replaceAll("\"", "").trim();
    	croppingImg(httpclient, imgCode);
    	swiftToAdvanceMode(httpclient);
    }
    
    private static String[] uploadIDCard(HttpClient httpclient) throws Exception {
    	String[] words = null;
        HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/uploadfilebyticket?opcode=1&type=2&t=iframe-uploadfilebyticket&lang=zh_CN&formid=1");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("uploadfile", new FileBody(new File("/Users/syujohnny/Desktop/11B3.jpg")));
        httpost.setEntity(entity);

        HttpResponse response = httpclient.execute(httpost);

        HttpEntity entityResp = response.getEntity();
        System.out.println(entityResp.toString());
        BufferedReader reader = new BufferedReader(new InputStreamReader(entityResp.getContent()));
        String line = reader.readLine();
        while(line != null) {
        	String reg = "top.W.upload.suc(";
        	if(line.contains(reg)) {
        		String bingo = line.substring(line.indexOf(reg) + reg.length(), line.indexOf(");"));
        		words = bingo.split(",");
        		break;
        	}
        	line = reader.readLine();
        }

        EntityUtils.consume(entityResp);
        return words;
    }
    
    private static void submitDetailedInfo(HttpClient httpclient, String verifyCd, String masterId, String slaveId, String md5) throws Exception {
        HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/realname?action=submitrealname&lang=zh_CN");
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("name", "林娟"));
        nvps.add(new BasicNameValuePair("id", "532823198112093927"));
        nvps.add(new BasicNameValuePair("mobile", "+8618001863596"));
        nvps.add(new BasicNameValuePair("verify_code", verifyCd));
        nvps.add(new BasicNameValuePair("telephone", "021-66211785"));
        nvps.add(new BasicNameValuePair("company", "上海悍思企业管理咨询有限公司"));
        nvps.add(new BasicNameValuePair("job", "总经理"));
        nvps.add(new BasicNameValuePair("country", "中国"));
        nvps.add(new BasicNameValuePair("province", "上海"));
        nvps.add(new BasicNameValuePair("city", "嘉定"));
        nvps.add(new BasicNameValuePair("idtype", "1"));
        nvps.add(new BasicNameValuePair("masterid", masterId));
        nvps.add(new BasicNameValuePair("slaveid", slaveId));
        nvps.add(new BasicNameValuePair("md5", md5));
        nvps.add(new BasicNameValuePair("ajax", "1"));
        httpost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        entity.writeTo(System.out);
        EntityUtils.consume(entity);
    }
    
    private static void loadEmailVerifyTemplate(HttpClient httpclient) throws Exception {
        HttpGet httpget = new HttpGet("http://mp.weixin.qq.com/cgi-bin/activateemail?email=dXl5dHJ0cmdmZHNnZmpoaGdqZmhmZGdkQHdlaXhpbmRpbmdjYW4uY29t&ticket=efcf7b82be0c62040e0355fed9db51087e48f35c");
        HttpResponse resp = httpclient.execute(httpget);
        HttpEntity entityImg = resp.getEntity();
        EntityUtils.consume(entityImg);
    }
    
    private static String[] uploadImg(HttpClient httpclient) throws Exception {
    	String[] words = null;
        HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/uploadheadimg?cgi=uploadheadimg&type=2&t=iframe-setting&lang=zh_CN&share=square");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("filename", new FileBody(new File("/Users/syujohnny/Desktop/2457331_085922644000_2.jpg"), "image/jpeg"));
        httpost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpost);

        HttpEntity entityResp = response.getEntity();
        BufferedReader reader = new BufferedReader(new InputStreamReader(entityResp.getContent()));
        String line = reader.readLine();
        while(line != null) {
        	String reg = "top.W.upload.suc(";
        	if(line.contains(reg)) {
        		String bingo = line.substring(line.indexOf(reg) + reg.length(), line.indexOf(");"));
        		words = bingo.split(",");
        		break;
        	}
        	line = reader.readLine();
        }

        EntityUtils.consume(entityResp);
        return words;
    }
    
    private static void croppingImg(HttpClient httpclient, String imgCode) throws Exception {
        HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/cropimg?t=ajax-response");
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("fid", imgCode));
        nvps.add(new BasicNameValuePair("width", "1024"));
        nvps.add(new BasicNameValuePair("height", "1024"));
        nvps.add(new BasicNameValuePair("x", "0"));
        nvps.add(new BasicNameValuePair("y", "0"));
        nvps.add(new BasicNameValuePair("ajax", "1"));
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        entity.writeTo(System.out);
        EntityUtils.consume(entity);
//    	response.getEntity().writeTo(System.out);
    }
    
    private static void swiftToAdvanceMode(HttpClient httpclient) throws Exception {
        HttpPost httpost1 = new HttpPost("http://mp.weixin.qq.com/cgi-bin/operadvancedfunc?op=switch&lang=zh_CN");
        List <NameValuePair> nvps1 = new ArrayList <NameValuePair>();
        nvps1.add(new BasicNameValuePair("flag", "0"));
        nvps1.add(new BasicNameValuePair("type", "1"));
        nvps1.add(new BasicNameValuePair("ajax", "1"));
        httpost1.setEntity(new UrlEncodedFormEntity(nvps1, "utf-8"));
        HttpResponse response1 = httpclient.execute(httpost1);
        HttpEntity entity1 = response1.getEntity();
        EntityUtils.consume(entity1);
        
        HttpPost httpost = new HttpPost("http://mp.weixin.qq.com/cgi-bin/callbackprofile?t=ajax-response&lang=zh_CN");
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("url", "http://ddstore.vicp.net/lansaowucan/wxmpGate/index"));
        nvps.add(new BasicNameValuePair("token", "1234321fvc"));
        nvps.add(new BasicNameValuePair("ajax", "1"));
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        HttpPost httpost3 = new HttpPost("http://mp.weixin.qq.com/cgi-bin/operadvancedfunc?op=switch&lang=zh_CN");
        List <NameValuePair> nvps3 = new ArrayList <NameValuePair>();
        nvps3.add(new BasicNameValuePair("flag", "1"));
        nvps3.add(new BasicNameValuePair("type", "2"));
        nvps3.add(new BasicNameValuePair("ajax", "1"));
        httpost3.setEntity(new UrlEncodedFormEntity(nvps3, "utf-8"));
        HttpResponse response3 = httpclient.execute(httpost3);
        HttpEntity entity3 = response3.getEntity();
        EntityUtils.consume(entity3);
    }
    
}
